using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace AuthService.Infrastructure.Services;

/// <summary>
/// Consul后台服务
/// 负责服务的自动注册和注销
/// </summary>
public class ConsulHostedService : IHostedService
{
    private readonly IConsulServiceRegistry _consulServiceRegistry;
    private readonly ILogger<ConsulHostedService> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="consulServiceRegistry">Consul服务注册</param>
    /// <param name="logger">日志记录器</param>
    public ConsulHostedService(IConsulServiceRegistry consulServiceRegistry, ILogger<ConsulHostedService> logger)
    {
        _consulServiceRegistry = consulServiceRegistry;
        _logger = logger;
    }

    /// <summary>
    /// 启动服务时注册到Consul
    /// </summary>
    /// <param name="cancellationToken">取消令牌</param>
    /// <returns>任务</returns>
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        try
        {
            _logger.LogInformation("开始注册服务到Consul...");
            
            var success = await _consulServiceRegistry.RegisterServiceAsync(cancellationToken);
            
            if (success)
            {
                _logger.LogInformation("服务注册到Consul成功");
            }
            else
            {
                _logger.LogError("服务注册到Consul失败");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "服务注册到Consul时发生异常");
        }
    }

    /// <summary>
    /// 停止服务时从Consul注销
    /// </summary>
    /// <param name="cancellationToken">取消令牌</param>
    /// <returns>任务</returns>
    public async Task StopAsync(CancellationToken cancellationToken)
    {
        try
        {
            _logger.LogInformation("开始从Consul注销服务...");
            
            var success = await _consulServiceRegistry.DeregisterServiceAsync(cancellationToken);
            
            if (success)
            {
                _logger.LogInformation("服务从Consul注销成功");
            }
            else
            {
                _logger.LogError("服务从Consul注销失败");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "服务从Consul注销时发生异常");
        }
    }
}
